<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="姓名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.phone" placeholder="号码" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.number" placeholder="数字" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
     
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
    </div>

    <el-table
      :header-cell-style="{ background: '#ffffff',color:'#000000' }"
      :key="tableKey"
      :row-class-name="tableRowClassName"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;font-size: 15px;box-shadow: 1px 1px 8px #cdcdcd;border: 0px;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="发票通知" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ }}</span>
        </template>
      </el-table-column> -->

     
      <!-- <el-table-column label="发票号" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.number }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="开票单位名称" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="纳税识别码" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.taxNo }}</span>
        </template>
      </el-table-column>     

      <el-table-column label="发票金额" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.consumeFee }}</span>
        </template>
      </el-table-column>  

      <el-table-column label="邮箱" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.recipientsEmail }}</span>
        </template>
      </el-table-column>  


       <el-table-column label="发票状态" min-width="150px">
        <template slot-scope="{row}">
        <el-tag v-if="row.status == '0'" size="medium" type="danger">未开票</el-tag>
        <el-tag v-else-if="row.status == '1'" size="medium" type="Warning">已申请开票</el-tag>
        <el-tag v-else-if="row.status == '2'" size="medium" type="Warning">已打印</el-tag>
        <el-tag v-else-if="row.status == '3'" size="medium" type="Warning">已寄出</el-tag>
        <el-tag v-else-if="row.status == '4'" size="medium" type="success">开票完成</el-tag>
        <el-tag v-else size="medium" type="Info">未知状态</el-tag>
        </template>
      </el-table-column>
    
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            Edit
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="getList" /> -->

    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination layout="total,sizes,prev, pager,next,jumper"  style="margin-top: 10px;" :page-size="pageSize" :total="total" :page-sizes="[10, 20, 30, 40]" @size-change="handlePageChange" @current-change="handleNoChange"></el-pagination>
      </el-col>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        
        <el-form-item label="电话" prop="phone">
          <el-select v-model="temp.phone" class="filter-item" placeholder="Please select">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间" prop="createDate">
          <el-date-picker v-model="temp.createDate" type="datetime" placeholder="Please pick a date" />
        </el-form-item>

        

        <el-form-item label="数字">
          <el-select v-model="temp.number" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="Remark">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style>
  .el-table .warning-row{
    background:#fff5ee;
  }
  .el-table--enable-row-hover .el-table__body tr:hover > td{
    background-color: #fdc091;
    
  }
  .el-table__body tr.current-row>td{
    background-color: #fdc091;
    
  }
</style>

<script>
import { lcinvoiceList } from '@/api/order'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { loadinvoiceApi } from "@/api/car";


const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 20,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        name: undefined,
        phone: undefined,
        number: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
  //  this.getList()
  },
  mounted: function() {
    this.$nextTick(function() {
      this.loadinvoice(this.pageNo, this.pageSize);
    });
  },
  methods: {
    // getList() {
    //   this.listLoading = true
    //   lcinvoiceList(this.listQuery).then(response => {
    //     this.list = response.data.list
    //     this.total = response.data.total

    //     // Just to simulate the time of the request
    //     setTimeout(() => {
    //       this.listLoading = false
    //     }, 1.5 * 1000)
    //   })
    // },
    tableRowClassName({row, rowIndex}) {
        if (rowIndex%2 == 0) {
          return 'warning-row';
        } 
        return '';
      },

//列表页码的触发事件
    handlePageChange(pageSize) {
      this.pageSize = pageSize;
      this.loadinvoice(this.pageNo, this.pageSize);
    },
    handleNoChange(pageNo) {
      this.pageNo = pageNo;
      this.loadinvoice(this.pageNo, this.pageSize);
    },
    handleTableChange(val) {
      this.multipleSelection = val;
    },
    loadinvoice(pageNo, pageSize) {
      let _this = this;
      _this.loading = true;
      loadinvoiceApi({ pageNo: pageNo, pageSize: pageSize,
        roleCode:this.$store.state.mainpart.key }).then(
        (response) => {
          _this.list = response.data.dataList;
          _this.total = response.data.totalNum;
          setTimeout(() => {
            _this.listLoading = false;
          }, 1 * 1000);
        }
      );
    },
    //////////////////////////


    handleFilter() {
      this.listQuery.pageNo = 1
   //   this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addCar(this.temp).then(() => {
    //        this.getList();
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateCar(this.temp).then(() => {
     //      this.getList();
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {

      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{

            deleteCar({"id":row.id}).then(() => {
       //             this.getList();
                    this.dialogFormVisible = false
                    this.$notify({
                      title: 'Success',
                      message: 'Delete Successfully',
                      type: 'success',
                      duration: 2000
                    })
                  })
        })
       
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
       axios({
              method: "GET",
              url: '/car/export',
              params: this.listQuery,
              headers:{pacargle:getToken()},
              responseType: 'blob' //返回是个文件
            }).then(response => {
              this.download(response) //then直接下载，方法在下边
            })
    },
    download (res) {
        let blob = new Blob([res.data], { type: "text/xls,charset=UTF-8" });//type是文件类，详情可以参阅blob文件类型
        // 创建新的URL并指向File对象或者Blob对象的地址
        const blobURL = window.URL.createObjectURL(blob)
        // 创建a标签，用于跳转至下载链接
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]))
        // 兼容：某些浏览器不支持HTML5的download属性
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        // 挂载a标签
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL)
      },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
